package com.zhentao.file.service.impl;

import com.zhentao.file.config.MinioConfig;
import com.zhentao.file.config.MinioconfigProperties;
import com.zhentao.file.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;

import java.io.InputStream;
import java.util.UUID;

/*
 *云计算
 *魏子纹
 *2025/6/10
 */

@EnableConfigurationProperties(MinioconfigProperties.class)//该注解用于启用配置属性绑定功能，将 application.properties 或 application.yml 中与 MinioconfigProperties 类相关的配置自动映射到该类的字段上。
@Import(MinioConfig.class)
public class FileStorageServiceImpl implements FileStorageService {
    @Autowired
    private MinioconfigProperties minioconfigProperties;

    @Autowired
    private MinioClient minioClient;

    @SneakyThrows
    @Override
    public String uploadHtmlFile(String fileName, InputStream inputStream) {
       //处理文件名
        fileName = UUID.randomUUID() + fileName;


        //文件的上传操作
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName) //文件名字
                .bucket(minioconfigProperties.getBucket())
                .contentType("text/html")
                .stream(inputStream, inputStream.
                        available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        //url
        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());

        return path;

    }
    @Override
    @SneakyThrows
    public String uploadImageFile(String fileName, InputStream inputStream) {

        //文件名的处理

        fileName = UUID.randomUUID()+ fileName;

        //文件的上传操作
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(fileName) //文件名字
                .bucket(minioconfigProperties.getBucket())
                .contentType("image/jpg")
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        //url
        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());

        return path;
    }
}
